var express = require('express');
var router = express.Router();

//引入模型
const userModel = require("../models/user");

const NodeRSA = require('node-rsa');
const key = new NodeRSA({b: 512});
// 提供加密的填充方案
key.setOptions({ encryptionScheme: 'pkcs1' });

/* GET users listing. */
//注册
router.post('/registry', function (req, res) {
  //判断用户是否存在
  let userExit = false;
  let uId = '0000';
  userModel.find({}, { userInfo: 1, _id: 0 }, (err, doc, next) => {
    doc.forEach(val => {
      if (val.userInfo.name === req.body.uname) {
        userExit = true;
      }
    })
    if (!userExit) {
      //确定用户id
      userModel.find({}, (err, doc) => {
        if (err) throw err;
        if (doc++ < 10) {
          uId = '000' + doc;
        } else if (doc >= 10 && doc <= 100) {
          uId = '00' + doc;
        } else {
          uId = '0' + doc;
        }
        console.log(uId);
        //添加用户
        // console.log(userModel);
        //构造一个用户的实例
        const user = new userModel({
          "userId": uId,
          "userInfo": {
            name: req.body.uname,
            pwd: req.body.upwd,
            sex: true,
            add: "",
            profile: "",
          },
          "userPets": [],
          "userCart": [],
          "userOrder": [],
          "userQuestions": [],
        })
        //存的是实例
        user.save((err) => {
          if (err) throw err;
          res.json({
            status: 0,
            msg: '用户添加成功',
          })
        });
      }).count();
    } else {
      res.json({
        status: 2,
        msg: '用户已存在',
      });
    }
  });
});
//预登录
router.get('/key', function (req, res) {
  let publicKey = key.exportKey('public')  //生成公钥
  console.log(publicKey);
  res.json({
    publicKey:publicKey
  })
});
//登录
router.post('/login', function (req, res) {
  // 连接数据库，将账号密码做匹配，返回结果
  const { info } = req.body;
  let decrypted = key.decrypt(info, 'utf8'); //解密
  const {uname, upwd} = JSON.parse(decrypted);

  //判断用户是否存在
  let uId;
  userModel.find({}, { userInfo: 1, userId: 1, _id: 0 }, (err, doc, next) => {
    doc.forEach(val => {
      if (val.userInfo.name === uname) {
        uId = val.userId;
      }
    })
    if (uId) {
      userModel.find({ userId: uId }, (err, doc) => {
        if (doc[0].userInfo.pwd === upwd) {
          res.json({
            status: 0,
            msg: '登陆成功',
            result: {
              userId: doc[0].userId,
              userInfo:doc[0].userInfo,
            }
          });
        } else {
          res.json({
            status: 4,
            msg: '用户密码错误',
          });
        }
      })
    } else {
      res.json({
        status: 3,
        msg: '用户不存在',
      });
    }
  });
});
//请求用户名
router.get('/username', function (req, res, next) {
  userModel.find({userId:req.query.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userInfo.name,
    })
  });
});
//所有问题
router.get('/allquestions', function (req, res, next) {
  userModel.find({}, (err, doc) => {
    if (err) throw err;
    let arr = [];
    doc.forEach(val => {
      //处理问题列表加上userId
      let newarr=val.userQuestions.map((item) => {
        return {...item,"userId": val.userId}
      })
      arr.splice(arr.length,0,...newarr);
    })
    
    res.json({
      status: 0,
      result: arr,
    })
  });
});
//用户问题
router.get('/userquestions', function (req, res, next) {
  userModel.find({userId:req.query.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userQuestions,
    })
  });
});
//更新用户问题
router.post('/updateque', function (req, res, next) {
  //get req.query
  //post req.body
  //处理用户问题数组
  let qarr = [];
  userModel.find({userId:req.body.uid}, (err, doc) => {
    if (err) throw err;
    qarr = doc[0].userQuestions;
    // 生成问题id
    let qid = "";
    if (qarr.length < 10) {
      qid = '0' + (qarr.length+1);
    } else{
      qid = (qarr.length+1) + '';
    }
    qarr.push({
      qid: qid,
      ...req.body.qobj,
      queAnswers:[],
      //获取时间戳
      queTime:Date.now()+'',
    })
    userModel.update({userId:req.body.uid},{ $set: { userQuestions: qarr } }, (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: '问题添加成功',
      })
    });
  });
});
//请求问题回答
router.get('/queanswers', function (req, res, next) {
  userModel.find({ userId: req.query.uid }, (err, doc) => {
    let anslist = [];
    doc[0].userQuestions.forEach(val => {
      console.log(val,req.query.queid);
      if (val.qid === req.query.queid) {
        anslist = val.queAnswers;
      }
    })
    if (err) throw err;
    res.json({
      status: 0,
      result: anslist,
    })
  });
});
//问题回答添加
router.post('/updateans', function (req, res, next) {
  //get req.query
  //post req.body
  //处理用户问题数组
  userModel.find({userId:req.body.quid}, (err, doc) => {
    if (err) throw err;
    //筛选问题回答
    let aarr = [];
    doc[0].userQuestions.forEach(val => {
      if (val.qid == req.body.qid) {
        aarr = val.queAnswers;
      }
    })
    // 生成回答id
    let aid = "";
    if (aarr.length < 10) {
      aid = '0' + (aarr.length+1);
    } else{
      aid = (aarr.length+1) + '';
    }
    aarr.push({
      aid: aid,
      ...req.body.aobj,
      //获取时间戳
      ansTime:Date.now()+'',
    })

    //更新用户问题列表
    let qarr = [];
    doc[0].userQuestions.forEach(val => {
      if (val.qid == req.body.qid) {
        let arr = val;
        arr.queAnswers=aarr;
        qarr.push(arr);
      } else {
        qarr.push(val);
      }
    })

    userModel.update({userId:req.body.quid},{ $set: { userQuestions: qarr } }, (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: '回答添加成功',
      })
    });
  });
});
//请求用户信息
router.get('/userinfo', function (req, res, next) {
  userModel.find({userId:req.query.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userInfo,
    })
  });
});
//更新用户信息
router.post('/updateinfo', function (req, res, next) {
  //get req.query
  //post req.body
  
  userModel.find({ userId: req.body.uid }, (err, doc) => {
    if (err) throw err;
    //处理用户对象
    console.log(doc[0].userInfo.pwd);
    let userObj = {
      ...req.body.uobj,
      //获取数据密码
      pwd: doc[0].userInfo.pwd,
    }
    userModel.update({userId:req.body.uid},{ $set: { userInfo: userObj } }, (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: '信息修改成功',
      })
    });
  });
  
});
//我的宠物请求
router.get('/minepets', function (req, res, next) {
  userModel.find({userId:req.query.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userPets,
    })
  });
});
//添加宠物
router.post('/addpet', function (req, res) {
  //判断用户是否存在
  let petId = '00';
  userModel.find({ userId: req.body.uid }, { userPets: 1, _id: 0 }, (err, doc, next) => {
    if (err) throw err;
    if (doc[0].userPets.length < 10) {
      //确定宠物id
      if (doc[0].userPets.length < 10) {
        petId = '0' + (doc[0].userPets.length+1);
      }
      let petArr = doc[0].userPets;
      petArr.push({
        "petId" : petId,
        "petName" : req.body.pname,
        "petSex" : req.body.psex,
        "petBreed" : req.body.pbreed,
        "petBirth" : req.body.pbirth,
        "petArrive" : req.body.parrive,
        "petSterilization" : req.body.pster
      })
      // 添加宠物
      userModel.update({ userId: req.body.uid }, { $set: { userPets: petArr } },  err => {
        if (err) throw err;
        res.json({
          status: 0,
          msg: '宠物添加成功',
        });
      })
    } else {
      res.json({
        status: 5,
        msg: '宠物太多拉',
      });
    }
  });
});
//获取购物车列表
router.post('/cartlist', function (req, res, next) {
  //get req.query
  //post req.body
  userModel.find({userId:req.body.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userCart,
    })
  });
});
//更新购物车列表
router.post('/updatecart', function (req, res, next) {
  //get req.query
  //post req.body
  userModel.update({userId:req.body.uid},{ $set: { userCart: req.body.carr } }, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      msg: '购物车更新成功',
    })
  });
});
//获取订单列表
router.post('/orderlist', function (req, res, next) {
  //get req.query
  //post req.body
  userModel.find({userId:req.body.uid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc[0].userOrder,
    })
  });
});
//更新订单列表
router.post('/updateorder', function (req, res, next) {
  //get req.query
  //post req.body
  //处理订单数组
  let oarr = [];
  userModel.find({userId:req.body.uid}, (err, doc) => {
    if (err) throw err;
    oarr = doc[0].userOrder;
    // console.log(oarr);
    oarr.push({
      productList: req.body.plist,
      //获取时间戳
      orderTime:Date.now()+'',
    })
    console.log(oarr);
    userModel.update({userId:req.body.uid},{ $set: { userOrder: oarr } }, (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: '订单添加成功',
      })
    });
  });
});
module.exports = router;
